﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using UnitOfWorkEF.SqlServer.Domain;

namespace Microsoft.Extensions.DependencyInjection
{
    public static partial class UnitOfWorkSqlServerServiceCollectionExtensions
    {
        public static IUnitOfWorkSqlServerBuilder AddDbContext<TUintOfWorkContext>(this IUnitOfWorkSqlServerBuilder unitOfWorkSqlServerBuilder,
            Action<DbContextOptionsBuilder> optionsAction = null,
            ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
            ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
            where TUintOfWorkContext : UnitOfWorkDbContext
        {
            if (unitOfWorkSqlServerBuilder == null) throw new ArgumentNullException(nameof(unitOfWorkSqlServerBuilder));
            unitOfWorkSqlServerBuilder.UnitOfWorkBuilder.Services.AddDbContext<TUintOfWorkContext>(optionsAction, contextLifetime, optionsLifetime);
            return unitOfWorkSqlServerBuilder;
        }
        public static IUnitOfWorkDefaultConfigurationBuilder AddDefaultDbContext(this IUnitOfWorkSqlServerBuilder unitOfWorkSqlServerBuilder,
            Action<DbContextOptionsBuilder> optionsAction = null,
            ServiceLifetime contextLifetime = ServiceLifetime.Scoped,
            ServiceLifetime optionsLifetime = ServiceLifetime.Scoped)
        {
            if (unitOfWorkSqlServerBuilder == null) throw new ArgumentNullException(nameof(unitOfWorkSqlServerBuilder));
            unitOfWorkSqlServerBuilder.AddDbContext<DefaultUnitWorkDbContext>(optionsAction, contextLifetime, optionsLifetime);
            return new DefaultUnitOfWorkDefaultConfigurationBuilder(unitOfWorkSqlServerBuilder);
        }
        public static IUnitOfWorkDefaultConfigurationBuilder AddEntityTypeConfiguration(this IUnitOfWorkDefaultConfigurationBuilder unitOfWorkSqlServerDefaultConfigurationBuilder, Action<IEntityTypeCollection> config)
        {
            if (unitOfWorkSqlServerDefaultConfigurationBuilder == null) throw new ArgumentNullException(nameof(unitOfWorkSqlServerDefaultConfigurationBuilder));

            var configurations = new DefaultEntityTypeCollection();
            config?.Invoke(configurations);
            unitOfWorkSqlServerDefaultConfigurationBuilder.UnitOfWorkSqlServerBuilder.UnitOfWorkBuilder.Services.AddSingleton<IEnumerable<IEntityTypeConfiguration<Entity>>>(configurations.GetCollection);

            return unitOfWorkSqlServerDefaultConfigurationBuilder;
        }
        public static IUnitOfWorkSqlServerBuilder AddUnitOfWorkSqlServerEntityFrameworkCore(this IUnitOfWorkBuilder  unitOfWorkBuilder)
        {
            if (unitOfWorkBuilder == null) throw new ArgumentNullException(nameof(unitOfWorkBuilder));
            unitOfWorkBuilder.Services.AddEntityFrameworkSqlServer();
            return new DefaultUnitOfWorkSqlServerBuilder(unitOfWorkBuilder);
        }
    }
}
